package t10086.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import t10086.Data.Pop.COLLISION;
import t10086.Model.Entity.CollisionRecord;
import t10086.Service.CollisionService;
import t10086.Service.DeliveryRecordService;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class FailedController {
    private final static BlockingQueue<COLLISION> popMsgQueue = new LinkedBlockingQueue<>();
    private final DeliveryRecordService deliveryRecordService;
    private final CollisionService collisionService;
    public static void putPopMsg(COLLISION collision) {
        popMsgQueue.offer(collision);

    }

    @Autowired
    public FailedController(DeliveryRecordService deliveryRecordService, CollisionService collisionService) {
        this.deliveryRecordService = deliveryRecordService;
        this.collisionService = collisionService;
    }

    @Scheduled(fixedRate = 500)
    public void run() {
        while (!popMsgQueue.isEmpty()) {
            COLLISION collision = popMsgQueue.poll();
            if (collision != null) {
                deliveryRecordService.deliveryFailed(collision.getSerialNumber1());
                collisionService.save(new CollisionRecord(collision));
            }
        }
    }
}
